package com.xd.dubbo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"com.xd.dubbo.mapper.orderDB"}, sqlSessionFactoryRef = "orderSqlSessionFactory")
public class OrderDataSourceConfig {


    @Bean("orderDataSource")
    public DataSource createUserDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("xhfd2019");
        dataSource.setUrl("jdbc:mysql://xianghongfood.com:3306/order?useUnicode=true&characterEncoding=utf8");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setInitialSize(3);
        dataSource.setMaxActive(5);
        dataSource.setUseGlobalDataSourceStat(true);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setValidationQuery("SELECT 1 FROM DUAL");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(5);
        return dataSource;
    }

    @Bean("orderSqlSessionFactory")
    @Primary
    public SqlSessionFactory localSqlSessionFactory(@Qualifier("orderDataSource") DataSource primaryDatasource) throws Exception {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(primaryDatasource);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.xd.dubbo.entity");
        // TODO 注意，请自行开启此注释
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/orderDB/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }


    @Bean("orderTransactionManager")
    public DataSourceTransactionManager serverTransactionManager(@Qualifier("orderDataSource") DataSource primaryDatasource) {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(primaryDatasource);
        return transactionManager;
    }

}
